'use client';

import type { TMetadata } from '@/types';
import { useQuery } from '@tanstack/react-query';
import { clientQueryAllMenu } from '@/services/api';
import type { IMenu } from '@/interfaces';
import NavbarAdminPage from '@/app/[locale]/admin/navbar';
import ListConfigAdminPage from '@/app/[locale]/admin/config/list';
import { NavbarPage } from '@/app/[locale]/navbar';
import FooterPage from '@/app/[locale]/footer';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import { ConfigAdminContext } from '@/contexts/admin/config';

export default function ConfigAdminPage({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <NavbarPage metadata={metadata} />
      <ConfigAdmin metadata={metadata} />
      <FooterPage metadata={metadata} />
    </>
  );
}

const ConfigAdmin = ({ metadata }: { metadata: TMetadata }) => {
  const clientQueryMenusQuery = useQuery(
    metadata.all['menus'].k,
    async (context) => {
      return (await clientQueryAllMenu()) as IMenu[];
    },
    {
      initialData: metadata.all['menus'].v as IMenu[],
    },
  );

  if (clientQueryMenusQuery.data) {
    return (
      <>
        <ConfigAdminContext.Provider value={{ metadata }}>
          <div className="container-fluid">
            <div className="vstack gap-4">
              <NavbarAdminPage menus={clientQueryMenusQuery.data} />

              <div className="row">
                <div className="col">
                  <div className="card">
                    <div className="card-body">
                      <h6 className="card-subtitle mb-2 text-muted">
                        配置总数
                      </h6>
                      <h5 className="card-title">9</h5>
                    </div>
                  </div>
                </div>
              </div>

              <ListConfigAdminPage />

              <div></div>
            </div>
          </div>
        </ConfigAdminContext.Provider>
      </>
    );
  }

  if (clientQueryMenusQuery.error) {
    return <Alert message={clientQueryMenusQuery.error} type="error" />;
  }

  return <AlertLoad />;
};
